<template>
  <div class="dashboard">
    <el-card class="welcome-card">
      <div class="welcome-content">
        <h2>管理员控制台</h2>
        <p>欢迎回来，管理员！这里可以查看平台各项数据统计。</p>
      </div>
    </el-card>

    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon users-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalUsers || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon orders-icon">
              <i class="el-icon-shopping-cart-full"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalOrders || 0 }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon revenue-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">¥{{ formatCurrency(stats.totalRevenue || 0) }}</div>
              <div class="stat-label">总营收(元)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon products-icon">
              <i class="el-icon-goods"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalGoods || 0 }}</div>
              <div class="stat-label">商品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-header">
            <span>用户角色分布</span>
          </div>
          <div class="chart-container">
            <div ref="roleChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-header">
            <span>最近三个月订单趋势</span>
          </div>
          <div class="chart-container">
            <div ref="orderTrendChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getDashboardStats, getRecentThreeMonthsOrdersStats } from '@/apis/admin.js'

const stats = ref({})
const roleChart = ref(null)
const orderTrendChart = ref(null)
let roleChartInstance = null
let orderTrendChartInstance = null

onMounted(() => {
  fetchData()
  fetchOrderTrendData()
})

onBeforeUnmount(() => {
  if (roleChartInstance) {
    roleChartInstance.dispose()
  }
  if (orderTrendChartInstance) {
    orderTrendChartInstance.dispose()
  }
})

const fetchData = async () => {
  try {
    const response = await getDashboardStats()
    if (response.code === 200) {
      stats.value = response.data
      drawRoleChart()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

const fetchOrderTrendData = async () => {
  try {
    const response = await getRecentThreeMonthsOrdersStats()
    if (response.code === 200) {
      drawOrderTrendChart(response.data)
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取订单趋势数据失败')
  }
}

const drawRoleChart = () => {
  // 确保DOM已经渲染
  nextTick(() => {
    if (roleChart.value) {
      roleChartInstance = echarts.init(roleChart.value)
      
      // 处理角色分布数据
      const roleData = stats.value.userByRole || []
      const chartData = roleData.map(item => {
        // 角色名中英文映射
        const roleNameMap = {
          'admin': '管理员',
          'user': '普通用户',
          'expert': '专家'
        }
        return {
          name: roleNameMap[item.role] || item.role || '未知',
          value: item.count || 0
        }
      })
      
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          bottom: 'bottom'
        },
        series: [
          {
            name: '用户角色分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartData
          }
        ]
      }
      
      roleChartInstance.setOption(option)
    }
  })
}

const drawOrderTrendChart = (data) => {
  nextTick(() => {
    if (orderTrendChart.value) {
      orderTrendChartInstance = echarts.init(orderTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.months || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: data.orderCounts || [],
            type: 'line',
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(64, 158, 255, 0.8)'
                },
                {
                  offset: 1,
                  color: 'rgba(64, 158, 255, 0.1)'
                }
              ])
            },
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      orderTrendChartInstance.setOption(option)
    }
  })
}

// 格式化货币显示
const formatCurrency = (value) => {
  return parseFloat(value).toFixed(2);
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.welcome-content h2 {
  font-size: 24px;
  margin-bottom: 10px;
}

.welcome-content p {
  font-size: 16px;
  opacity: 0.9;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.users-icon {
  background: linear-gradient(135deg, #409eff, #64b5f6);
}

.orders-icon {
  background: linear-gradient(135deg, #e53935, #fb8c00);
}

.revenue-icon {
  background: linear-gradient(135deg, #43a047, #7cb342);
}

.products-icon {
  background: linear-gradient(135deg, #8e24aa, #d81b60);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  padding: 10px 0;
}

.chart-container {
  height: 300px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>